#!/usr/bin/env python
# coding:utf-8
from PoboAPI import *
from datetime import date
import datetime
import numpy as np
import time



#开始时间，用于初始化一些参数
def OnStart(context) :
    print "I\'m starting..."
    #登录交易账号，需在主页用户管理中设置账号，并把期货测试替换成您的账户名称
    context.myacc = None
    if context.accounts.has_key("回测期货") :
        print "登录交易账号[回测期货]"
        if context.accounts["回测期货"].Login() :
            context.myacc = context.accounts["回测期货"]

def OnMarketQuotationInitialEx(context, exchange,daynight):
    if exchange != 'SHFE':
        return
    #获取主力合约
    g.code = GetMainContract('SHFE', 'rb',20)
    #订阅K线数据，用于驱动OnBar事件
    SubscribeBar(g.code, BarType.Day)
    
def GetBuyAvgPrice(AccountsName,code):
    import numpy as np
    option = PBObj()
    option.contract=code
    pos=AccountsName.GetPositions(option)
    price=[]
    volume=[]
    for p in pos:
      if p.bstype.BuySellFlag=='0' and p.bstype.TodayFlag ==False:
        price.append(p.openavgprice)
        volume.append(p.volume)
      if p.bstype.BuySellFlag=='0' and p.bstype.TodayFlag ==True:
        price.append(p.openavgprice)
        volume.append(p.volume)
    pri=np.array(price)
    vol=np.array(volume)
    print "pri "+str(pri)+" vol "+str(vol)
    if sum(vol)!=0:
      return sum(pri*vol)/sum(vol)
    else:
      return

    
    
#实时行情事件，当有新行情出现时调用该事件Ex
def OnBar(context,code,bartype) :
    #过滤掉不需要的行情通知
    if code != g.code:
        return
    dyndata = GetQuote(g.code)
    #计算均
    
    
    MA = GetIndicator("MA",code,params=(1,5),bar_type = BarType.Day)
    
    EXPMAdata = GetIndicator("EXPMA",code,params=(8,12,20,21),bar_type = BarType.Day)
    EXPMAdata1 = GetIndicator("EXPMA",code,params=(21,49),bar_type = BarType.Day)
    #the coders said for EXPMA it has to take no less than 2 parameters and no more than 4 parameters
    #maybe they can fix this design later
    
    EXPMA1=MA["MA(1)"]
    EXPMA2=EXPMAdata["MA2"]
    EXPMA3=EXPMAdata["MA3"]
    EXPMA4=EXPMAdata["MA4"]
    EXPMA5=EXPMAdata1["MA1"]
    EXPMA6=EXPMAdata1["MA2"]
    
    print "check  "+str(EXPMA5[-1])
    print "check  "+str(EXPMA6[-1])
    
    today = date.today()
 
    pos=10 #positions you want to open/close
    
    #####checking positions#############
    option = PBObj()
    #option.buysellflag = '0'
    positions = context.accounts["回测期货"].GetPositions(option)
    
    if len(positions)>0:
        
        buyavgprice=GetBuyAvgPrice(context.myacc,g.code)
        
        
        print "average buying price "+str(buyavgprice)
    
    
    
    
    if len(EXPMA4)<2:
        return
    #ma1上穿ma2时买入螺纹主力1手
    elif EXPMA1[-1] >= EXPMA2[-1] and EXPMA1[-2]<EXPMA2[-2] and EXPMA1[-1] >= EXPMA3[-1] and EXPMA1[-2]<EXPMA3[-2] and EXPMA1[-1] >= EXPMA4[-1] and EXPMA1[-2]<EXPMA4[-2]:
        print "ma1 "+str(EXPMA1[-1])+" ema5 "+str(EXPMA2[-1])+" ema10 "+str(EXPMA3[-1])+" ema20 "+str(EXPMA4[-1])
        QuickInsertOrder(context.myacc,g.code,'buy','open',dyndata.now,pos)
        #time.sleep(60*60*24*5)
        #QuickInsertOrder(context.myacc,g.code,'sell','close',dyndata.now,pos)
        
        
    #ma1下穿ma2时卖出平仓
    elif EXPMA1[-1] <= EXPMA2[-1] and EXPMA1[-2]>EXPMA2[-2] and EXPMA1[-1] <= EXPMA3[-1] and EXPMA1[-2]>EXPMA3[-2] and EXPMA1[-1] <= EXPMA4[-1] and EXPMA1[-2]>EXPMA4[-2]:
        print "ma1 "+str(EXPMA1[-1])+" ema5 "+str(EXPMA2[-1])+" ema10 "+str(EXPMA3[-1])+" ema20 "+str(EXPMA4[-1])
        QuickInsertOrder(context.myacc,g.code,'sell','close',dyndata.now,pos)
        #time.sleep(60*60*24*5)
        #QuickInsertOrder(context.myacc,g.code,'buy','open',dyndata.now,pos)
